import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/flags.dart';
import 'package:management/const/init.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/user/LoginResponse.dart';
import 'package:management/main.dart';

class SplashScreen extends StatefulWidget {
  const SplashScreen({Key? key}) : super(key: key);

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
        vsync: this, duration: const Duration(seconds: 1, milliseconds: 500))
      ..repeat();
    super.initState();
    GlobalInit.init().then((value) => startNextPage());
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Theme.of(context).colorScheme.background,
        child: Column(
          children: [
            const SizedBox(
              height: 230,
            ),
            Image.asset('assets/images/Group.png'),
            const SizedBox(
              height: 140,
            ),
            RotationTransition(
                turns: _controller,
                child: Image.asset('assets/images/Vector.png'))
          ],
        ));
  }

  Future startNextPage() async {
    final String? refreshToken = GlobalInit.getSpData(SPFlag.refreshToken);
    if (refreshToken != null) {
      MyHttpClient.getRefreshByToken(refreshToken)
          .then((value) => _refreshToken(value));
      Get.offNamed(RouteConfig.homeScreen);
    } else {
      Get.offNamed(RouteConfig.welcomeScreen);
    }
  }

  Future _refreshToken(LoginResponse value) async {
    if (value.code == 200) {
      GlobalInit.saveSpData(SPFlag.expiresIn, value.data!.expiresIn!);
      GlobalInit.saveSpData(SPFlag.accessToken, value.data!.accessToken!);
    }
  }
}
